package com.example.csetpp.interceptor;

import com.example.csetpp.constants.JWTConstant;
import com.example.csetpp.constants.WeChatConstant;
import com.example.csetpp.exception.LoginFailedException;
import com.example.csetpp.utils.JwtUtil;
import com.example.csetpp.utils.UserIdHolder;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserIdHolder.removeCurrentId();
    }


    //校验JWT生产的token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("authorization");

        System.out.println(request.getHeader("Authorization"));

        // 检查 token 是否缺失
        if (token == null || token.isEmpty()) {
            log.info("token缺失");
            response.setStatus(401);
            throw new LoginFailedException("尚未登录");
        }
        
        try {
            log.info("token:{}", token);
            Claims claims = JwtUtil.parseJWT(JWTConstant.SECRET_KEY, token);
            Long userId = Long.valueOf(claims.get(WeChatConstant.USER_ID).toString());
            log.info("用户ID:{}",userId);
            UserIdHolder.setCurrentId(userId);
            return true;
        }
        catch (Exception e) {
            log.info("token过期: {}", e.getMessage());
            response.setStatus(401);
            throw new LoginFailedException("登录状态已过期，请重新登录");
        }
    }
}
